from DB import *
from AOFRecordFactory import *

# AOF文件中保存的是所有數據庫寫操作的順序以及對應的參數

# TODO:
# 追加記一筆的數據
# 追加分類、賬戶、預算修改的數據
# 增加AOF頭部內容
# 文件切割
# 壓縮

# AOF文件由頭部和若干條記錄組成（未實現）
# 頭部的格式為：
# | VERSION | COMPRESS_TYPE | PADDING | HEAD_LENGTH | NEXT_AOF_NAME | MD5SUM |
# |   1     |      1        |    2    |    32       |      32       |    8   |
#
# 記錄的格式為：（未實現）
# | VERSION | RECORD_TYPE | PADDING | DATA_LEN | DATA |
# |   1     |      1      |    2    |    32    | VAR  |

    
class AOFManager:
    ''' Append Only File
    保存用戶所有寫操作，可以用來從頭回復數據'''
    def __init__(self, aofName):
        self.aofName = aofName

    def init(self):
        '''等到需要實現AOF頭部的時候再完成'''
        pass

    def addIncomeRecord(self, record):
        aofRecord = AddIncomeRecordToAOFRecord(record)
        self.__addRecordCore(aofRecord, AOFRecordType.AddIncomeRecord)
        
    def addPaymentRecord(self, record):
        aofRecord = AddPaymentRecordToAOFRecord(record)
        self.__addRecordCore(aofRecord, AOFRecordType.AddPaymentRecord)
        
    def addTransferRecord(self, record):
        aofRecord = AddTransferrecordToAOFRecord(record)
        self.__addRecordCore(aofRecord, AOFRecordType.AddTransferRecord)

    def deleteIncomeRecord(self, recordId):
        aofRecord = DeleteIncomeRecordToAOFRecord(recordId)
        self.__addRecordCore(aofRecord, AOFRecordType.DeleteIncomeRecord)

    def deletePaymentRecord(self, recordId):
        aofRecord = DeletePaymentRecordToAOFRecord(recordId)
        self.__addRecordCore(aofRecord, AOFRecordType.DeletePaymentReocrd)

    def deleteTransferRecord(self, recordId):
        aofRecord = DeleteTransferRecordToAOFRecord(recordId)
        self.__addRecordCore(aofRecord, AOFRecordType.DeleteTransferRecord)
        
    def setBudget(self, budgetList):
        aofRecord = SetBudgetToAOFRecord(budgetList)
        self.__addRecordCore(aofRecord, AOFRecordType.SetBudget)

    def readAOF(self):
        aof = open(self.aofName, mode='r')
        while True:
            line = aof.readline()
            if line == '':
                break
            recordType, args = ParseAOFRecord(line)
            if recordType == AOFRecordType.AddIncomeRecord:
                Global.db.addIncomeRecord(args[0])
            elif recordType == AOFRecordType.AddPaymentRecord:
                Global.db.addPaymentRecord(args[0])
            elif recordType == AOFRecordType.AddTransferRecord:
                Global.db.addTransferRecord(args[0])
            elif recordType == AOFRecordType.DeleteIncomeRecord:
                Global.db.deleteIncomeRecord(args[0])
            elif recordType == AOFRecordType.DeletePaymentReocrd:
                Global.db.deletePaymentRecord(args[0])
            elif recordType == AOFRecordType.DeleteTransferRecord:
                Global.db.deleteTransferRecord(args[0])
            elif recordType == AOFRecordType.SetBudget:
                Global.db.setBudget(args[0])
            else:
                raise ValueError('Unknow AOFRecordType: %d'%(recordType))
        aof.close()

    def __addRecordCore(self, aofRecord, aofRecordType):
        '''把aofRecord轉換成字符串，并記錄寫入AOF文件中'''
        aofStr = toAOFaofString(aofRecordType, aofRecord)
        aof = open(self.aofName, mode='a')
        aof.write(aofStr)
        aof.close()